""" Render HTML strings, ElementTrees and minidom Documents
on the Reinteract shell.

Copyright 2007 Eduardo de Oliveira Padoan
Licence: GPL v2 or above.
"""

import os
import subprocess

try:
    from elementtree import ElementTree as ET
except ImportError:
    try:
        # Python 2.5
        import xml.etree.ElementTree as ET
    except ImportError:
        ET = None

import gtk
import gtkhtml2

from reinteract.custom_result import CustomResult

__all__ = ['RenderResult', 'render']


def stringfy(obj):
    if isinstance(obj, basestring):
        return obj

    try:
        # ElementTree
        return ET.tostring(obj.getroot())
    except AttributeError:
        # Either ET is None or obj isnt a ElementTree
        try:
            return obj.toxml() # DOM
        except AttributeError:
            return str(obj)


def open_url(doc, url):
    """Open the url on the default web browser.
    """
    if os.path.exists('/usr/bin/gnome-open'):
        command = 'gnome-open'
    else:
        command = 'x-www-browser'
    subprocess.Popen([command, url], close_fds=True,
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)


class RenderResult(CustomResult):
    def __init__(self, html):
        self.html = stringfy(html)

    def create_widget(self):

        doc = gtkhtml2.Document()
        doc.clear()
        doc.open_stream('text/html')
        doc.write_stream(self.html)
        doc.close_stream()

        doc.connect('link_clicked', open_url)

        view = gtkhtml2.View()
        view.set_document(doc)

        sw = gtk.ScrolledWindow()
        sw.set_vadjustment(view.get_vadjustment())
        sw.set_hadjustment(view.get_hadjustment())
        sw.set_size_request(400, 200)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

        sw.add(view)
        sw.show_all()

        return sw


def render(html):
    return RenderResult(html)

